<template>
  <div>
    <a-form layout="inline">
      <a-form-item>
        <a-button
          v-if="logined"
          @click="showModal('新增',1)"
          type="primary">
          <template #icon><PlusOutlined /></template>
          新增
        </a-button>
      </a-form-item>
        <a-select
          mode="multiple"
          v-model:value="projectIds"
          :maxTagCount="1"
          :allowClear="true"
          placeholder="项目分类"
          style="width:270px;float:right;"
        >
          <a-select-option v-for="item in projectOptions" :key="item.value">
            {{ item.title }}
          </a-select-option>
        </a-select>
    </a-form>
    <a-table
      :rowKey="record=>record.serialNumber"
      :loading="loading"
      :columns="softListColumns"
      :data-source="filteredDataSource"
      :scroll="{y:650}"
      :pagination="pagination"
      :customRow="logined ? customRow : () => {}"
      size="small"
      style="margin-top:10px">
      <template #ip="{ record }">
        <a-button
          :disabled="(record.disabled * 1 === 1 || record.ip === '') ? true : false"
          @click="handleServiceTo(`${record.ip}`,record.disabled)"
          type="link"
          size="small">
          {{record.ip}}
        </a-button>
      </template>
      <template #disabled="{ record }">
        <a-tag color="#87d068" v-if="record.disabled * 1 === 0">有</a-tag>
        <a-tag color="#f50" v-if="record.disabled * 1 === 1">无</a-tag>
        <!-- {{record.disabled * 1 === 0 ? '未配置' : '已配置'}} -->
      </template>
      <template #action="{ record }">
        <span>
          <a-button
            v-if="logined"
            type="primary"
            size="small"
            style="margin-right:10px;"
            @click="showModal('修改',3,record)">修改
          </a-button>
          <a-popconfirm
            :title="`确定删除${record.name}?`"
            ok-text="确定"
            cancel-text="取消"
            @confirm="confirmDelete(record)"
            >
            <a-button type="danger" size="small" v-if="logined">删除
            </a-button>
          </a-popconfirm>
        </span>
      </template>
    </a-table>
    <a-modal
      :title="modalConfig.title"
      v-model:visible="modalConfig.visible"
      width="800px"
      :confirm-loading="loading"
      :destroyOnClose="true"
      @ok="handleOk">
      <SoftListSetting
        ref="RefSoftSetting"
        :loading="loading"
        :type="modalConfig.type"
        :softRow="modalConfig.softRow"
        :softIds="modalConfig.softIds"
        @handle-soft="handleSoft" />
    </a-modal>
  </div>
</template>

<script>
import SoftListSetting from './SoftListSetting'
import { softListColumns } from '../soft.config'
import { onMounted, reactive, getCurrentInstance, ref, computed, watch } from 'vue'
import { useStore } from 'vuex'
// import { Modal } from 'ant-design-vue'
import {
  PlusOutlined
} from '@ant-design/icons-vue'
export default {
  components: {
    PlusOutlined,
    SoftListSetting
  },
  props: {
    projectId: {
      type: String,
      required: true
    }
  },
  setup (props) {
    const { proxy } = getCurrentInstance()
    const store = useStore()
    const projectIds = ref([])
    // eslint-disable-next-line prefer-const
    let loading = ref(false)
    // eslint-disable-next-line prefer-const
    let dataSource = ref([])
    const modalConfig = reactive({
      title: '',
      visible: false,
      type: 1,
      softRow: {},
      softIds: []
    })
    const pagination = reactive({
      size: '20',
      showSizeChanger: true
    })
    const dragStartRow = ref({})
    const dropRow = ref({})
    const filteredDataSource = computed(() => {
      if (projectIds.value.length === 0) {
        return dataSource.value
      } else {
        const selectedData = dataSource.value.filter(item => {
          return projectIds.value.indexOf(item.projectId) !== -1
        })
        return selectedData
      }
    })
    onMounted(() => {
      loading.value = true
      searchSoftList()
    })
    const searchSoftList = async () => {
      const { errCode, data } = await proxy.$root.$axios.getSoftList()
      if (errCode * 1 === 0) {
        dataSource.value = data.map((item, index) => {
          return {
            ...item,
            projectName: item.project.name,
            serialNumber: index + 1
          }
        })
        modalConfig.softIds = data.map(item => item.id)
      }
      loading.value = false
    }
    const handleSoft = async (formState) => {
      loading.value = true
      let errCode = ''
      if (modalConfig.type === 1) {
        const data = await proxy.$root.$axios.addSoft({ ...formState })
        errCode = data.errCode
      } else if (modalConfig.type === 3) {
        const data = await proxy.$root.$axios.modifySoft(formState.id, { ...formState })
        errCode = data.errCode
      }
      if (errCode * 1 === 0) {
        proxy.$root.$message.success('操作成功')
        searchSoftList()
        modalConfig.visible = false
      }
      loading.value = false
    }
    const confirmDelete = async (record) => {
      loading.value = true
      const { errCode } = await proxy.$root.$axios.deleteSoft(record.id)
      if (errCode * 1 === 0) {
        proxy.$root.$message.success('操作成功')
        searchSoftList()
      }
      loading.value = false
    }
    const showModal = (title, type, record) => {
      modalConfig.title = '软件' + title
      modalConfig.type = type
      modalConfig.softRow = record
      modalConfig.visible = true
    }
    const RefSoftSetting = ref(null)
    const handleOk = () => {
      RefSoftSetting.value.onSubmit()
    }
    watch(() => props.projectId, (val) => {
      projectIds.value = [val]
    })
    const customRow = (record, index) => {
      return {
        onMouseenter: (event) => {
          // 兼容IE
          var ev = event || window.event
          ev.target.draggable = true
        },
        onDragstart: (event) => {
          // 兼容IE
          var ev = event || window.event
          // 阻止冒泡
          ev.stopPropagation()
          // 得到源目标数据
          dragStartRow.value = { ...record }
        },
        onDragover: (event) => {
          // 兼容 IE
          var ev = event || window.event
          // 阻止默认行
          ev.preventDefault()
        },
        onDrop: (event) => {
          // 兼容IE
          var ev = event || window.event
          // 阻止冒泡
          ev.stopPropagation()
          // 得到目标数据
          dropRow.value = { ...record }
          const dragStartRowIndex = dragStartRow.value.serialNumber - 1
          const dragStartRowId = dragStartRow.value.id
          const dropRowIndex = record.serialNumber - 1
          const dropRowId = record.id
          dataSource.value[dragStartRowIndex] = { ...record }
          dataSource.value[dropRowIndex] = dragStartRow.value
          dataSource.value = dataSource.value.map((item, index) => {
            return {
              ...item,
              serialNumber: index + 1
            }
          })
          proxy.$root.$axios.draggedSoft({
            [dragStartRowId]: dropRowIndex,
            [dropRowId]: dragStartRowIndex
          })
        }
      }
    }
    return {
      logined: computed(() => store.state.logined),
      softListColumns,
      projectOptions: computed(() => store.state.projectOptions),
      projectIds,
      loading,
      filteredDataSource,
      modalConfig,
      handleSoft,
      confirmDelete,
      showModal,
      RefSoftSetting,
      handleOk,
      handleServiceTo (url, disabled) {
        if (disabled * 1 === 1) {
          proxy.$root.$message.error('当前服务器未配置，无法打开')
          return
        }
        window.open(url)
      },
      props,
      pagination,
      customRow
    }
  }
}
</script>

<style lang='less' scoped>

</style>
